package com.example;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取数据库表名的工具类
 *
 * @author czx
 * @since 2022/5/6 11:41
 */

public class MysqlJdbcUtils {
    /**
     * 返回表名的列表
     *
     * @param databaseUrl 数据库地址
     * @param databaseName 数据库名
     * @param user 用户名
     * @param password 密码
     * @return 表名的列表
     */
    public static List<String> getTableName(String databaseUrl,String databaseName,String user,String password) {
        List<String> tableList = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");     //加载MYSQL JDBC驱动程序
            System.out.println("Success loading Mysql Driver!");
        } catch (Exception e) {
            System.out.print("Error loading Mysql Driver!");
            e.printStackTrace();
        }
        try {
            Connection connect = DriverManager.getConnection("jdbc:mysql://" +
                    databaseUrl +"/" + databaseName + "?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true", user, password);
            // 连接URL为 jdbc:mysql//服务器地址/数据库名 ，后面的2个参数分别是登陆用户名和密码
            System.out.println("Success connect Mysql server!");
            Statement stmt = connect.createStatement();
            ResultSet rs = stmt.executeQuery("select table_name from information_schema.tables where table_schema='" + databaseName + "'");
            while (rs.next()) {
                System.out.print("\"" + rs.getString("TABLE_NAME") + "\",");
                tableList.add(rs.getString("TABLE_NAME"));
//                System.out.println(rs.getString("tables"));
            }
            System.out.println();
        } catch (Exception e) {
            System.out.print("get data error!");
            e.printStackTrace();
        }
        return tableList;
    }
}

